import React, { Component } from 'react';
import Child1 from './Child1';
import Child2 from './Child2';
class index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      showCoponent: false,
      keys: ['child1', 'child2'],
    };
  }
  componentDidMount() {
    this.setState({
      data: {
        child1: {
          id: '111',
          name: 'child1--三高',
        },
        child2: {
          id: '222',
          name: 'child2--沈总',
        },
      },
      showCoponent: true,
    });
  }
  renderComponent() {
    const { data, keys } = this.state;
    return keys.map(key => {
      let Component = null;
      let props = {};
      switch (key) {
        case 'child1':
          Component = Child1;
          props = {
            data: data.child1,
          };
          break;
        case 'child2':
          Component = Child2;
          props = {
            data: data.child2,
          };
          break;
        default:
          break;
      }
      return <Component {...props} />;
    });
  }
  render() {
    const { showCoponent, data } = this.state;
    return (
      <div>
        {showCoponent && this.renderComponent()}
        {/* {showCoponent && <Child1 data={data.child1} />}
                {showCoponent && <Child2 data={data.child2} />} */}
        <button
          onClick={() => {
            this.setState({
              data: {
                child1: {
                  id: '111',
                  name: 'child1--三高',
                },
                child2: {
                  id: '222',
                  name: 'child2--沈总',
                },
              },
            });
          }}
        >
          设置state
        </button>
      </div>
    );
  }
}

export default index;
